#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include "lockgroup.hpp"
#include "LOG.hpp"
#include <string.h>
#include <string>
#include "InetAddr.h"

using namespace std;


void Usege(string argv)
{
    cout << argv << "sever_ip + sever_port" << endl;
}

int main(int args,char* argv[])
{
    EnableCout();
    if(args != 3)
    {
        Usege(argv[0]);
        exit(1);
    }

    string ip = argv[1];
    uint16_t port = stoi(argv[2]);

    //1.创建套接字
    int socketfd = socket(AF_INET,SOCK_STREAM,0);
    if(socketfd < 0)
    {
        LOG(FATAL,"socketfd fail");
        exit(2);
    }
    LOG(INFO,"socket success :%d",socketfd);

    //client 要bind 但不用自己显式bind
    //构建服务器结构信息
    struct sockaddr_in sever;
    bzero(&sever,sizeof(sever));
    sever.sin_family = AF_INET;
    sever.sin_port = htons(port);
    sever.sin_addr.s_addr = inet_addr(ip.c_str());

    //和服务器sever建立连接
    int n = connect(socketfd,(struct sockaddr*)&sever,sizeof(sever));
    if(n < 0)
    {
        LOG(FATAL,"connect error");
        exit(3);
    }

    //客户端通信
    while(1)
    {
        cout << "please enter :";
        string line;
        getline(cin,line);
        //把line 发给服务端    
        //客户端就不用 read write了，认识新的
        ssize_t s = send(socketfd,line.c_str(),line.size(),0);
        if(s > 0)
        {
            //发成功，并且要收到服务器端的消息
            char buffer[1024];
            ssize_t m = recv(socketfd,buffer,sizeof(buffer),0);
            if(m > 0)
            {
                //收到成功，打出来
                buffer[m] = 0;
                cout << buffer <<endl;
            }
            else
            {
                break;
            }
        }
        else 
        {
            break;
        }
    }
    close(socketfd);
    return 0;

}